package 动态规划;

public class 摆动序列 {
    //初级动态
    public  static int wiggleMaxLength(int[] nums) {
        int n = nums.length;
        int[] down = new int[n];
        down[0] = 1;
        int[] up = new int[n];
        up[0] = 1;
        int last = nums[0];
        for (int i = 1; i < n; i++) {
            if (nums[i] > last){
                down[i] = down[i-1];
                up[i] = down[i-1]+1;
            }else if (nums[i] < last){
                up[i] = up[i-1];
                down[i] = up[i-1]+1;
            }else {
                up[i] = up[i-1];
                down[i] = down[i-1];
            }
            last = nums[i];
        }
        return Math.max(down[n-1],up[n-1]);
    }

    //优化动态
    public  static int wiggleMaxLength1(int[] nums) {
        int n = nums.length;
        if (n<2){
            return n;
        }
        int up = 1,down =1;
        for (int i = 1; i < n; i++) {
            if (nums[i] > nums[i-1]){
                up = down +1;
            }else if (nums[i] < nums[i-1]){
                down = up + 1;
            }
        }
        return Math.max(up,down);
    }

    public static int wiggleMaxLength2(int[] nums) {
        int n = nums.length;
        if (n < 2) {
            return n;
        }
        int prevdiff = nums[1] - nums[0];
        int ret = prevdiff != 0 ? 2 : 1;
        for (int i = 2; i < n; i++) {
            int diff = nums[i] - nums[i - 1];
            if ((diff > 0 && prevdiff <= 0) || (diff < 0 && prevdiff >= 0)) {
                ret++;
                //只有满足峰或者谷,才交换差值
                prevdiff = diff;
            }
        }
        return ret;
    }




    public static void main(String[] args) {
        int[] nums = {1,1,2,2,3,3};
        System.out.println(wiggleMaxLength2(nums));
    }
}
